'use client'

import { useState, useEffect, useCallback } from 'react'
import { signIn, useSession, signOut } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import Button from '@/components/ui/Button'
import { toast } from 'react-hot-toast'
import Link from 'next/link'

export default function LoginPage() {
  const router = useRouter()
  const { data: session, status, update } = useSession()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [remember, setRemember] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [isLogoutLoading, setIsLogoutLoading] = useState(false)
  const [errorMsg, setErrorMsg] = useState('')
  const [wasLoggedOut, setWasLoggedOut] = useState(false)
  
  // 检测到已注销状态时进行额外的清理
  useEffect(() => {
    // 解析URL参数
    const urlParams = new URLSearchParams(window.location.search)
    const timeout = urlParams.get('timeout')
    const loggedOut = urlParams.get('loggedOut')
    const allDevices = urlParams.get('allDevices')
    
    if (loggedOut === 'true') {
      setWasLoggedOut(true)
      
      if (allDevices === 'true') {
        toast.success('您已成功在所有设备上注销')
      } else {
        toast.success('您已成功注销')
      }
      
      // 额外清理，确保不会重新自动登录
      const cleanupState = async () => {
        try {
          // 清除所有相关cookie
          const cookies = document.cookie.split(';')
          cookies.forEach(cookie => {
            const cookieName = cookie.split('=')[0].trim()
            if (cookieName.includes('next-auth') || 
                cookieName.includes('session') || 
                cookieName.includes('csrf')) {
              // 确保同时为不同路径设置过期cookie
              document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;`
              document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/api;`
              document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/api/auth;`
              document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/api/auth/session;`
            }
          })
          
          // 强制刷新会话状态
          if (status === 'authenticated') {
            await signOut({ redirect: false })
            console.log('检测到URL注销参数，强制清除会话状态')
          }
          
          // 清除本地和会话存储
          localStorage.clear()
          sessionStorage.clear()
          
          // 强制更新URL以防止重新导航到之前的页面
          if (!window.location.search.includes('t=')) {
            const timestamp = Date.now()
            window.history.replaceState(
              {}, 
              '', 
              `${window.location.pathname}?loggedOut=true&t=${timestamp}`
            )
          }
        } catch (e) {
          console.error('清理会话状态时出错:', e)
        }
      }
      
      cleanupState()
    } else if (timeout === 'true') {
      toast.error('您的会话已过期，请重新登录')
    }
  }, [status])

  // 在已注销情况下或进入页面时检查会话状态
  useEffect(() => {
    if (wasLoggedOut && status === 'authenticated') {
      console.log('检测到注销后仍处于已登录状态，强制注销')
      signOut({ redirect: false })
    }
    
    // 如果处于登录状态，提供注销选项通知
    if (status === 'authenticated' && !wasLoggedOut) {
      toast.success('您已经登录，可以直接进入系统或选择注销')
    }
  }, [status, wasLoggedOut])

  // 使用防抖处理避免多次点击
  const handleLogout = useCallback(async () => {
    // 防止重复点击
    if (isLoading || isLogoutLoading) return
    
    console.log('点击了普通注销按钮')
    toast.loading('正在注销...', { id: 'logout' })
    
    try {
      setIsLoading(true)
      
      // 先清除所有cookie（客户端操作）
      const cookies = document.cookie.split(';')
      const nowTime = new Date(0).toUTCString()
      
      cookies.forEach(cookie => {
        const cookieName = cookie.split('=')[0].trim()
        if (cookieName.includes('next-auth') || 
            cookieName.includes('session') || 
            cookieName.includes('csrf')) {
          console.log('手动清除cookie:', cookieName)
          document.cookie = `${cookieName}=; expires=${nowTime}; path=/; domain=${window.location.hostname}; secure; samesite=lax`
          document.cookie = `${cookieName}=; expires=${nowTime}; path=/; secure; samesite=lax`
          document.cookie = `${cookieName}=; expires=${nowTime}; path=/api; secure; samesite=lax`
          document.cookie = `${cookieName}=; expires=${nowTime}; path=/api/auth; secure; samesite=lax`
        }
      })
      
      // 清除本地存储
      localStorage.clear()
      sessionStorage.clear()
      
      // 然后调用NextAuth的signOut
      await signOut({ redirect: false })
      toast.success('已成功注销', { id: 'logout' })
      
      // 添加延迟确保异步操作完成
      setTimeout(() => {
        console.log('执行硬重定向到登录页面')
        const timestamp = Date.now()
        // 使用强制刷新确保状态完全清除
        window.location.href = `/login?loggedOut=true&t=${timestamp}`
      }, 500)
    } catch (error) {
      console.error('注销失败:', error)
      toast.error('注销失败，请稍后重试', { id: 'logout' })
    } finally {
      setIsLoading(false)
    }
  }, [isLoading, isLogoutLoading])
  
  const handleLogoutAllDevices = useCallback(async () => {
    // 防止重复点击或正在加载时的点击
    if (isLoading || isLogoutLoading) return
    
    console.log('点击了在所有设备上注销按钮')
    
    // 添加确认对话框
    if (!window.confirm('确定要在所有设备上注销吗？这将终止您所有设备上的登录会话。')) {
      console.log('用户取消了在所有设备上注销操作')
      return
    }
    
    console.log('用户确认了在所有设备上注销操作，准备发送请求')
    
    try {
      // 显示处理中状态
      setIsLogoutLoading(true)
      toast.loading('正在处理注销请求...', { id: 'logout-all-toast' })
      
      // 生成唯一请求ID，防止缓存
      const requestId = Date.now().toString()
      
      console.log('发送注销所有设备请求，请求ID:', requestId)
      
      // 调用后端API完成注销所有设备的功能
      const response = await fetch(`/api/auth/logout-all?requestId=${requestId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'X-Request-ID': requestId
        },
        cache: 'no-store',
      })
      
      console.log('收到注销所有设备响应:', response.status, response.statusText)
      
      // 检查响应状态
      if (response.ok) {
        try {
          const data = await response.json()
          console.log('注销所有设备响应数据:', data)
          
          // 显示成功消息
          toast.success(data.message || '已成功在所有设备上注销', { id: 'logout-all-toast' })
          
          // 清除当前会话
          console.log('开始清除当前会话')
          await signOut({ redirect: false })
          
          // 强制重新加载页面以确保会话状态被完全清除
          console.log('正在重定向到登录页面')
          setTimeout(() => {
            window.location.href = '/login?loggedOut=true'
          }, 1000)
        } catch (parseError) {
          // 如果响应解析失败，但状态码是成功的，仍然视为成功
          console.warn('注销响应解析失败，但状态码是成功:', parseError)
          toast.success('已成功注销所有设备', { id: 'logout-all-toast' })
          
          // 清除当前会话并重定向
          await signOut({ redirect: false })
          setTimeout(() => window.location.href = '/login?loggedOut=true', 1000)
        }
      } else {
        // 处理错误响应
        try {
          const errorData = await response.json()
          console.error('注销失败, 服务器返回错误:', errorData)
          toast.error(errorData.error || '注销所有设备失败，请稍后重试', { id: 'logout-all-toast' })
        } catch (parseError) {
          console.error('注销失败，无法解析错误响应:', parseError, '状态码:', response.status)
          toast.error(`注销所有设备失败: HTTP ${response.status}`, { id: 'logout-all-toast' })
        }
      }
    } catch (error) {
      console.error('注销所有设备请求失败 (网络错误):', error)
      toast.error('注销请求发送失败，请检查网络连接', { id: 'logout-all-toast' })
    } finally {
      setIsLogoutLoading(false)
    }
  }, [isLoading, isLogoutLoading])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setErrorMsg('')

    console.log('尝试登录:', { email, password: '******', remember })

    if (!email || !password) {
      setErrorMsg('请填写邮箱和密码');
      return;
    }

    try {
      const result = await signIn('credentials', {
        email,
        password,
        remember: remember.toString(),
        redirect: false,
      })

      console.log('登录结果:', result)

      if (result?.error) {
        setErrorMsg(result.error)
        toast.error(result.error)
      } else if (result?.ok) {
        toast.success('登录成功')
        router.replace('/')
        router.refresh()
      } else {
        setErrorMsg('登录请求发送失败')
        toast.error('登录请求发送失败')
      }
    } catch (error) {
      console.error('登录错误:', error)
      setErrorMsg(error instanceof Error ? error.message : '登录失败，请稍后重试')
      toast.error('登录失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 渲染页面
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            {status === 'authenticated' ? '您已登录' : '登录账号'}
          </h2>
          {status !== 'authenticated' && (
            <p className="mt-2 text-center text-sm text-gray-600">
              或{' '}
              <Link
                href="/register"
                className="font-medium text-primary-600 hover:text-primary-500"
              >
                注册新账号
              </Link>
            </p>
          )}
        </div>

        {errorMsg && (
          <div className="rounded-md bg-red-50 p-4 mb-4">
            <div className="text-sm text-red-700">{errorMsg}</div>
          </div>
        )}

        {status === 'authenticated' ? (
          <div className="mt-8 space-y-6">
            <div className="rounded-md bg-green-50 p-4">
              <p className="text-sm text-green-700">
                您已登录为 <strong>{session?.user?.email}</strong>
              </p>
              <p className="text-sm text-green-700 mt-1">
                角色: <strong>{session?.user?.role}</strong>
              </p>
            </div>
            <div className="flex space-x-4">
              <Button
                onClick={() => {
                  console.log('点击了返回主页按钮');
                  router.push('/');
                }}
                variant="primary"
                className="flex-1"
                disabled={isLoading || isLogoutLoading}
              >
                返回主页
              </Button>
              <Button
                onClick={async (e) => {
                  e.preventDefault();
                  console.log('点击了普通注销按钮 (直接调用)');
                  if (isLoading || isLogoutLoading) {
                    console.log('忽略点击，因为有操作正在进行中');
                    return;
                  }
                  
                  setIsLoading(true);
                  toast.loading('正在注销...', { id: 'logout-direct' });
                  
                  try {
                    await update(null); 
                    console.log('NextAuth session updated to null optimistically');

                    try {
                      localStorage.clear();
                      sessionStorage.clear();
                      console.log('本地存储和会话存储已清除');
                    } catch (err) {
                      console.error('清除存储失败:', err);
                    }

                    const timestamp = Date.now();
                    await signOut({ 
                      redirect: true, 
                      callbackUrl: `/login?loggedOut=true&t=${timestamp}` 
                    });
                    console.log('signOut 调用完成，NextAuth 将处理重定向');
                  } catch (error) {
                    console.error('注销失败 (直接调用):', error);
                    toast.error('注销失败，请稍后重试', { id: 'logout-direct' });
                    setIsLoading(false); 
                  }
                }}
                variant="outline"
                className="flex-1"
                disabled={isLoading || isLogoutLoading}
              >
                {isLoading ? '注销中...' : '注销登录'}
              </Button>
            </div>
            <Button
              onClick={async (e) => {
                e.preventDefault();
                console.log('点击了在所有设备上注销按钮 (直接调用)');
                if (isLoading || isLogoutLoading) {
                  console.log('忽略点击，因为有操作正在进行中');
                  return;
                }
                
                if (!window.confirm('确定要在所有设备上注销吗？这将终止您所有设备上的登录会话。')) {
                  console.log('用户取消了在所有设备上注销操作');
                  return;
                }
                
                console.log('用户确认了在所有设备上注销操作，准备发送请求');
                setIsLogoutLoading(true);
                toast.loading('正在处理注销请求...', { id: 'logout-all-direct' });
                
                try {
                  await update(null);
                  console.log('NextAuth session updated to null optimistically for logout-all');

                  try {
                    localStorage.clear();
                    sessionStorage.clear();
                    console.log('本地存储和会话存储已清除 (logout-all)');
                  } catch (err) {
                    console.error('清除存储失败 (logout-all):', err);
                  }

                  const requestId = Date.now().toString();
                  console.log('发送注销所有设备请求，请求ID:', requestId);
                  const response = await fetch(`/api/auth/logout-all?requestId=${requestId}`, {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json',
                      'Cache-Control': 'no-cache, no-store, must-revalidate',
                      'Pragma': 'no-cache',
                      'X-Request-ID': requestId
                    },
                    cache: 'no-store',
                    credentials: 'include', 
                  });
                  
                  console.log('收到注销所有设备响应:', response.status, response.statusText);

                  if (!response.ok) {
                    let errorMsg = `注销所有设备失败: HTTP ${response.status}`;
                    try {
                      const errorData = await response.json();
                      console.error('注销所有设备API失败, 服务器返回错误:', errorData);
                      errorMsg = errorData.error || errorMsg;
                    } catch (parseError) {
                      console.error('无法解析注销所有设备API的错误响应:', parseError);
                    }
                    toast.error(errorMsg, { id: 'logout-all-direct' });
                    setIsLogoutLoading(false);
                    return; 
                  }
                  
                  const data = await response.json();
                  console.log('注销所有设备API响应数据:', data);

                  const timestamp = Date.now();
                  await signOut({ 
                    redirect: true, 
                    callbackUrl: `/login?loggedOut=true&allDevices=true&t=${timestamp}` 
                  });
                  console.log('signOut (after logout-all) 调用完成，NextAuth 将处理重定向');

                } catch (error: any) {
                  console.error('注销所有设备请求失败 (直接调用):', error);
                  toast.error(error.message || '注销请求发送失败，请检查网络连接', { id: 'logout-all-direct' });
                  setIsLogoutLoading(false);
                }
              }}
              variant="outline"
              className="w-full mt-2 text-red-600 border-red-500 hover:bg-red-50 focus:ring-red-500"
              disabled={isLoading || isLogoutLoading}
            >
              {isLogoutLoading ? '注销中...' : '在所有设备上注销'}
            </Button>
          </div>
        ) : (
          <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
            <div className="rounded-md shadow-sm -space-y-px">
              <div>
                <label htmlFor="email" className="sr-only">
                  邮箱
                </label>
                <input
                  id="email"
                  name="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
                  placeholder="邮箱地址"
                />
              </div>
              <div>
                <label htmlFor="password" className="sr-only">
                  密码
                </label>
                <input
                  id="password"
                  name="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm"
                  placeholder="密码"
                />
              </div>
            </div>

            <div className="flex items-center">
              <input
                id="remember"
                name="remember"
                type="checkbox"
                checked={remember}
                onChange={(e) => setRemember(e.target.checked)}
                className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
              />
              <label htmlFor="remember" className="ml-2 block text-sm text-gray-900">
                记住登录状态（4小时）
              </label>
            </div>

            <div>
              <Button
                type="submit"
                className="w-full"
                disabled={isLoading}
              >
                {isLoading ? '登录中...' : '登录'}
              </Button>
            </div>
          </form>
        )}

        <div className="mt-4 text-center">
          <p className="text-xs text-gray-500">
            登录状态: {status === 'loading' ? '加载中...' : status === 'authenticated' ? '已登录' : '未登录'}
          </p>
        </div>
      </div>
    </div>
  )
} 